import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    SafeAreaView,
    Linking,
} from 'react-native';
import { Formik } from 'formik';
import { RRCToast ,RRCLoading} from 'react-native-overlayer';
import { RadioGroup, RadioButton } from 'react-native-flexi-radio-button'
import { getPixel, getScreenWidth, getScreenHeight, storeData, getData } from '../common/common';
import BaseComponent from '../component/BaseComponent';
import StorageUtil from '../util/StorageUtil';
import DeviceInfo from 'react-native-device-info';
import HttpUtil from '../util/HttpUtil';
import { get } from 'react-native-extra-dimensions-android';
const ipReg =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

const numReg = /^\+?[0-9][0-9]*$/;

export default class IpSetting extends BaseComponent {

    constructor(props){
        super(props);
        this.state={
            ip: '',
            port: '',
            project: '',
            isApply:false,
            applyPeople:'',
            applyReason:'',
            deviceUniqueId:DeviceInfo.getUniqueId().toUpperCase(),
            version:DeviceInfo.getVersion(),
            versionHintText:'',
            useMode: 0 ,
        }
    }

    async componentDidMount() {
        let ip = await StorageUtil.get('ip');
        let port = await StorageUtil.get('port');
        let project = await StorageUtil.get('project');
        let isApply = await StorageUtil.get('isApply');
        let useMode = await StorageUtil.get('useMode');
        this.setState({
            ip: ip,
            port: port,
            project: project,
            useMode:useMode || 0,
            // isApply:isApply,
        });
        if(ip && port && project){
            this.getVersion();
        }else{
            this.setState({
                versionHintText:'请设置正确的服务器地址'
            })
        }
    }


    onBackClicked = () => {
        this.props.navigation.navigate('Login');
        return true;
    }

    back = () =>{    
        this.props.navigation.navigate('Login');
    } 

    handleChange = (field) => {
        this.setState(field);
    }

    submit = () => {
        if(this.state.ip === null || this.state.ip === ''){
            RRCToast.show('请输入服务IP', 2, 3000);
            return;
        }
        // if(!ipReg.test(this.state.ip)){
        //     RRCToast.show('服务IP格式不正确', 2, 3000);
        //     return;
        // }
        if(this.state.port === null || this.state.port === ''){
            RRCToast.show('请输入服务端口', 2, 3000);
            return;
        }
        if(!numReg.test(this.state.port)){
            RRCToast.show('服务端口支持数字格式', 2, 3000);
            return;
        }

        StorageUtil.save('ip', this.state.ip);
        StorageUtil.save('port', this.state.port);
        StorageUtil.save('project', this.state.project);
        StorageUtil.save('useMode', this.state.useMode);        
        global.variables.server = this.state.ip + ':' + this.state.port + '/' + this.state.project;
        this.props.navigation.navigate('Login');
    }

    getVersion =()=>{
        if(this.state.ip === null || this.state.ip === ''){
            RRCToast.show('请输入服务IP', 2, 3000);
            return;
        }
        // if(!ipReg.test(this.state.ip)){
        //     RRCToast.show('服务IP格式不正确', 2, 3000);
        //     return;
        // }
        if(this.state.port === null || this.state.port === ''){
            RRCToast.show('请输入服务端口', 2, 3000);
            return;
        }
        if(!numReg.test(this.state.port)){
            RRCToast.show('服务端口支持数字格式', 2, 3000);
            return;
        }
        global.variables.server = this.state.ip + ':' + this.state.port + '/' + this.state.project;

        RRCLoading.setLoadingOptions({
            text: '请稍候',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })
        RRCLoading.show();
        HttpUtil.post('user/getVersion', null)
            .then(result => { 
                if(result.httpCode == 200){
                    RRCLoading.hide();
                    this.setState({
                        versionHintText:'请点击下载当前版本V'+result.data
                    })
                }else{
                    RRCLoading.hide();
                    RRCToast.show(result.msg?result.msg:'系统异常', 1, 7000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            })
    }

    apply=()=>{
        if(this.state.ip === null || this.state.ip === ''){
            RRCToast.show('请输入服务IP', 2, 3000);
            return;
        }
        // if(!ipReg.test(this.state.ip)){
        //     RRCToast.show('服务IP格式不正确', 2, 3000);
        //     return;
        // }
        if(this.state.port === null || this.state.port === ''){
            RRCToast.show('请输入服务端口', 2, 3000);
            return;
        }
        if(!numReg.test(this.state.port)){
            RRCToast.show('服务端口支持数字格式', 2, 3000);
            return;
        }
        if(this.state.applyPeople === null || this.state.applyPeople === ''){
            RRCToast.show('请输入申请人', 2, 3000);
            return;
        }

        if(this.state.applyReason === null || this.state.applyReason === ''){
            RRCToast.show('请输入申请原因', 2, 3000);
            return;
        }
        global.variables.server = this.state.ip + ':' + this.state.port + '/' + this.state.project;

        RRCLoading.setLoadingOptions({
            text: '请稍候',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })

        RRCLoading.show();
        
        let params = {
            code: this.state.deviceUniqueId,
            applyPeople:this.state.applyPeople,
            applyReason: this.state.applyReason,
        }

        HttpUtil.post('applyWhiteList', params)
            .then(result => { 
                if(result.httpCode == 200){
                    RRCLoading.hide();
                    RRCToast.show(result.msg?result.msg:'申请已提交申请', 2, 7000);
                    // StorageUtil.save('isApply', true);
                    // this.setState({
                    //     isApply:true,
                    // })
                }else{
                    RRCLoading.hide();
                    RRCToast.show(result.msg?result.msg:'系统异常', 1, 7000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            })

    }

    open = ()=>{
        let url = global.variables.server+'/api/downloadPage'
        Linking.openURL(url)
    }
    onModeSelect = (index,value)=>{
        this.setState({ 
            useMode: value,
        });
    }

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>
                        <TouchableOpacity onPress={() => this.back()}>
                            <Image source={ require('../images/back.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                        </TouchableOpacity>
                    </View>
                    <View style={{ width: getScreenWidth() - getPixel(110), justifyContent:'center', alignItems:'center' }}>
                        <Text style={{ fontSize: getPixel(17), color:'#333' }}>服务设置</Text>
                    </View>
                    <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>
                    </View>
                </View>
                <Formik
                initialValues={{ }}
                onSubmit={ values => this.submit(values) }
                >
                {({ handleChange, setFieldValue, handleBlur, handleSubmit, values }) => (
                    <View style={{ height: getPixel(204) }}>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>服务IP</Text>
                            <TextInput style={ styles.inputValue} placeholder="请输入服务IP" onChangeText={ text => this.handleChange({ ip: text })}  value={ this.state.ip } />
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>服务端口</Text>
                            <TextInput style={ styles.inputValue} placeholder="请输入服务端口" onChangeText={ text => this.handleChange({ port: text })}  value={ this.state.port } />
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>项目名</Text>
                            <TextInput style={ styles.inputValue} placeholder="请输入项目名称" onChangeText={ text => this.handleChange({ project: text })}  value={ this.state.project } />
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>设备ID</Text>
                            <Text style={ styles.inputValue} >{this.state.deviceUniqueId } </Text>
                        </View>
                        <View style={{flexDirection: 'row',alignItems:'center',height: getPixel(30),paddingLeft: getPixel(10),}}>
                            <Text style={{textAlign:'center',}}>模式选择</Text>
                        </View> 
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <RadioGroup
                                onSelect = {(index, value) => this.onModeSelect(index, value)}
                                size={15}
                                style={{flexDirection: 'row',justifyContent:'center',alignItems:'center',height: getPixel(30),paddingLeft: getPixel(10),}}
                                selectedIndex={this.state.useMode}
                            >
                                <RadioButton value={'0'}>
                                    <Text>在线</Text>
                                </RadioButton>

                                <RadioButton value={'1'}>
                                    <Text>离线</Text>
                                </RadioButton>
                            </RadioGroup>
                        </View>
                        <View style={{flexDirection: 'row',alignItems:'center',height: getPixel(30),paddingLeft: getPixel(10),}}>
                            <Text style={{textAlign:'center',}}>申请设备权限</Text>
                        </View> 
                        <View style={{display:this.state.isApply?'none':'flex',}}>
                            <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                                <Text style={ styles.inputLable }>申请人</Text>
                                <TextInput style={ styles.inputValue} placeholder="请输入申请人" onChangeText={ text => this.handleChange({ applyPeople: text })}  value={ this.state.applyPeople } />
                            </View>
                            <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                                <Text style={ styles.inputLable }>申请原因</Text>
                                <TextInput style={ styles.inputValue} placeholder="请输入申请原因" onChangeText={ text => this.handleChange({ applyReason: text })}  value={ this.state.applyReason } />
                            </View>
                            <View style={ [styles.formGroup, {flexDirection: 'row', justifyContent: 'center',borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                                <TouchableOpacity onPress={this.apply} style={{paddingLeft: getPixel(10), paddingRight: getPixel(10),alignItems: 'center',}}>
                                    <View style={[styles.buttonAdd,{width:getPixel(160),justifyContent:'center',height: getPixel(35), backgroundColor:'#518ba2'}]}>
                                        <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>申请权限</Text>
                                    </View>
                                </TouchableOpacity> 
                            </View>
                            <View style={{flexDirection: 'row',alignItems:'center',height: getPixel(30),paddingLeft: getPixel(10),}}>
                                <Text style={{textAlign:'center',}}>版本信息</Text>
                            </View> 
                            <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                                <TouchableOpacity onPress={this.getVersion} style={{height:getPixel(30),alignItems:'center',backgroundColor:'#518ba2',justifyContent:'center',borderRadius: getPixel(10),}}>
                                    <Text style={{fontSize: getPixel(15), width: getPixel(100), color: '#fff',textAlign:'center'}}>获取APP版本</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={(this.state.ip&&this.state.port&&this.state.project)?this.open:''} style={{paddingLeft:getPixel(10)}}>
                                    <Text style={{textDecorationLine:(this.state.ip&&this.state.port&&this.state.project)?'underline':'none', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}> {this.state.versionHintText}</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        {/* <View style={{flexDirection: 'row', alignItems: 'center', height: getPixel(50), paddingLeft: getPixel(10),paddingRight: getPixel(10),marginTop:getPixel(20)}}>
                                <TouchableOpacity onPress={this.getVersion} style={{height:getPixel(30),alignItems:'center',backgroundColor:'#4a69dd',justifyContent:'center',borderRadius: getPixel(10),}}>
                                    <Text style={{fontSize: getPixel(15), width: getPixel(100), color: '#00FF00',textAlign:'center'}}>获取APK版本</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={(this.state.ip&&this.state.port&&this.state.project)?this.open:''}>
                                    <Text style={{ color: '#00FF00', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}> {this.state.versionHintText}</Text>
                                </TouchableOpacity>
                        </View> */}
                        {/* <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>摄像头</Text>
                            <RadioGroup
                                onSelect = {(index, value) => this.onSelect(index, value)}
                                size={15}
                                style={{flexDirection: 'row'}}
                                selectedIndex={this.state.isCamera}
                            >
                                <RadioButton value={0}>
                                <Text>无</Text>
                                </RadioButton>

                                <RadioButton value={1}>
                                <Text>有</Text>
                                </RadioButton>
                            </RadioGroup>
                        </View> */}
                    </View>
                )}
                </Formik>
            
  
                <View style={styles.buttonGroup}>
                    <TouchableOpacity onPress={this.submit}>
                        <View style={styles.buttonAdd}>
                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>保存</Text>
                        </View>
                    </TouchableOpacity> 
                </View>
            </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    header: {
        height: getPixel(50),
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        flexDirection: 'row',
    },
    formGroup: {
        flexDirection: 'row',
        alignItems: 'center',
        height: getPixel(50),
        backgroundColor: '#FFF',
        paddingLeft: getPixel(10),
        paddingRight: getPixel(10),
    },
    inputLable: {
        fontSize: getPixel(15),
        width: getPixel(90),
        color: '#333',
    },
    inputValue: {
        fontSize: getPixel(15),
        width: getScreenWidth() - getPixel(110),
    },
    selectLable: {
        fontSize: getPixel(15),
        width: getPixel(90),
        color: '#333',
    },
    selectValue: {
        fontSize: getPixel(15),
        width: getScreenWidth() - getPixel(130),
    },
    selectIcon: {
        width: getPixel(25),
        alignItems: 'center',
    },
    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(20),
        paddingRight: getPixel(20),
        height: getPixel(60), 
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        position:'absolute',
        bottom: 0,
        
    },
    buttonAdd: {
        backgroundColor: '#4a69dd', 
        height: getPixel(40), 
        borderRadius: getPixel(10),
        width: (getScreenWidth() - 40),
    },
});